<template>
  <div ref="div" class="two">
    <dalogAdd :dialog-visible.sync="dialogVisibleAdd" @changePage="changeFn" />
    <dalogEdit ref="edit" :visible-edit.sync="dialogVisibleEdit" @changeData="changeData" />
    <el-card ref="el" style="margin-top:30px ;padding:15px">
      <el-form ref="form" :model="form">
        <el-row>
          <el-col :span="6"><div class="grid-content bg-purple">
            <el-form-item prop="name">
              <b>标签名称：</b><el-input v-model="form.name" style="width:200px" label="标签名称" placeholder="请输入内容" />
            </el-form-item>
          </div></el-col>
          <el-col :span="12">
            <b>活动地区:</b>
            <v-distpicker
              hide-area
              :province="province"
              :city="city"
              @province="onChangeProv"
              @city="onChangeCity"
            />
            <el-form-item prop="province">
              <el-input v-model="form.province" type="hidden" placeholder="请输入内容" style="display:none" />
            </el-form-item>
            <el-form-item prop="city">
              <el-input v-model="form.city" type="hidden" placeholder="请输入内容" style="display:none" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple-light">
              <el-form-item prop="enterprise">
                <b>企业简称：</b> <el-input v-model="form.enterprise" style="width:200px" label="企业简称" placeholder="请输入内容" />
              </el-form-item>
            </div></el-col>
        </el-row>
        <el-row style="margin-top:15px">
          <el-col :span="6">
            <el-form-item prop="region">
              <b>状态：</b>
              <el-select v-model="form.region" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6"><div class="grid-content bg-purple-light">
            <el-button @click="reset">清除所有</el-button>
            <el-button type="primary" @click="select">点击查询</el-button>
          </div></el-col>
          <el-col :span="6">
            <el-row type="flex" justify="end" style="visibility: hidden;">
              <el-col :span="6">1</el-col>
              <el-col :span="6">1</el-col>
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-row type="flex" justify="end">
              <el-button type="success" icon="el-icon-edit" @click="changeViseible">新增列表</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-alert
          title="共有16条信息"
          type="info"
          show-icon
          style="margin-top:15px"
        />
      </el-row>
      <el-row>
        <el-table
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            align="center"
            prop="id"
            label="序号"
            width="130"
          />
          <el-table-column
            prop="number"
            label="企业编号"
            width="130"
            align="center"
          />

          <el-table-column
            prop="shortName"
            label="企业简称"
            width="130"
            align="center"
          />
          <el-table-column
            prop="tags"
            label="标签"
            width="130"
            align="center"
          />
          <el-table-column
            prop="username"
            label="创建者"
            width="130"
            align="center"
          />
          <el-table-column
            prop="addDate"
            label="创建日期"
            width="130"
            align="center"
          />
          <el-table-column
            prop="remarks"
            label="备注"
            width="130"
            align="center"
          />
          <el-table-column
            prop="state"
            label="状态"
            width="130"
            align="center"
          />
          <el-table-column
            prop="address"
            label="操作"
            width="170"
            align="center"
          >
            <template slot-scope="{ row }">
              <el-button plain type="primary" icon="el-icon-edit" circle @click="changeEdit(row)" />
              <!-- 禁用和开启按钮切换的效果 -->
              <el-button v-if="row.state ==='开启'" plain type="success" icon="el-icon-check" circle @click="toggleStatus(row)" />
              <el-button v-else type="danger" icon="el-icon-close" circle @click="toggleStatus(row)" />
              <el-button plain type="danger" icon="el-icon-delete" circle @click="deleteAccount(row)" />
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <el-row type="flex" justify="center" style="margin-top:15px ;">
        <el-pagination
          :current-page="page.page"
          :page-size="page.pagesize"
          layout="prev, pager, next, jumper"
          :total="page.counts"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>
  </div>
</template>

<script>
import dalogAdd from './components/dalog-add.vue'
import dalogEdit from './components/dalog-edit.vue'
import VDistpicker from 'v-distpicker'
import { getCompanys, toggleCompanys, deleteCompanys } from '@/api/company'
export default {
  components: {
    dalogAdd,
    dalogEdit,
    VDistpicker
  },
  data() {
    return {
      // 处理后的查询数组，五个一组
      searchList: [],
      // 是否查询状态，解决点击分页器刷新页面bug
      isSearch: false,
      // 省数据
      province: null,
      // 市数据
      city: null,
      form: {
        enterprise: '',
        name: '',
        region: '',
        province: '',
        city: ''
      },
      options: [{
        value: '开启',
        label: '开启'
      }, {
        value: '禁用',
        label: '禁用'
      }],
      value: '',
      page: {
        page: 1, // 当前页码
        pagesize: 5, // 几条数据
        counts: 0 // 总数
      },
      companyList: [],
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      currentPage1: 5,
      // 表格
      tableData: []

    }
  },
  computed: {
    getCompanyData() {
      // map是可以操作数组内部的对象的某一个属性转化成目标值后在返回操作后的数组的
      return this.companyList.items.map((item) => {
        item.addDate = `${new Date(item.addDate).getFullYear()}-${new Date(item.addDate).getMonth()}-${new Date(item.addDate).getDate()}`
        item.state = item.state === 1 ? '开启' : '禁用'
        return item
      })
    }
  },
  created() {
    this.getCompanysList(this.page)
  },
  methods: {
    async select() {
      this.isSearch = true
      const res = await getCompanys({
        pagesize: 99999999999 // 几条数据
      })
      this.companyList = res
      const arr = this.companyList.items.filter(item => {
        if (this.form.name.trim() === '') {
          return true
        } else {
          return item.tags === this.form.name
        }
      }).filter(item => {
        if (this.form.enterprise.trim() === '') {
          return true
        } else {
          return item.shortName === this.form.enterprise
        }
      }).filter(item => {
        if (this.form.region.trim() === '') {
          return true
        } else {
          const a = item.state ? '开启' : '禁用'
          return a === this.form.region
        }
      })
      // 状态转化
      arr.map(item => {
        item.state = item.state === 1 ? '开启' : '禁用'
        return item
      })
      // arr 一个数组，保存了全部的数据但是我们一页只显示五条 所以要五个一组
      const cardList = arr
      this.page.counts = arr.length
      const newCardList = []
      for (var i = 0; i < cardList.length; i += 5) {
        newCardList.push(cardList.slice(i, i + 5))
      }
      // 将数组的第一页显示出来 剩下的在分页器中的监听事件中显示
      this.tableData = newCardList[0]
      this.searchList = newCardList
    },
    onChangeProv(e) {
      console.log(e)
      this.form.province = e.value
    },
    onChangeCity(e) {
      this.form.city = e.value
    },
    // 编辑后通知父亲刷新数据
    changeData() {
      this.getCompanysList(this.page)
    },
    changeFn() {
      // 添加后通知父亲调用自己的方法刷新数据
      this.getCompanysList(this.page)
    },
    // 创建一个获取数据列表的方法
    async getCompanysList(page) {
      try {
        const res = await getCompanys(page)
        console.log(res)
        this.page.counts = res.counts
        this.companyList = res
        this.tableData = this.getCompanyData
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 弹出框打开
    changeViseible() {
      this.dialogVisibleAdd = true
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(num) {
      // 得到这页是多少页，然后再发请求获得这一页的数据
      if (!this.isSearch) {
        this.page.page = num
        this.getCompanysList(this.page)
      }
      if (this.isSearch) {
        this.tableData = this.searchList[num - 1]
      }
    },
    // 编辑按钮
    changeEdit(row) {
      // 给子组件传去数据回填的id
      this.dialogVisibleEdit = true
      this.$refs.edit.getCompanysDetail(row.id)
    },
    async toggleStatus(row) {
      try {
        await this.$confirm('确认切换状态吗？')
        if (row.state === '开启') {
          await toggleCompanys({
            id: row.id,
            state: 0
          })
        } else {
          await toggleCompanys({
            id: row.id,
            state: 1
          })
        }
        this.getCompanysList(this.page)
        this.$message.success('状态切换成功')
      } catch (err) {
        this.$message('取消操作')
      }
    },
    async deleteAccount(row) {
      try {
        await this.$confirm('确认永久删除账户吗？')
        await deleteCompanys(row.id)
        this.getCompanysList(this.page)
        this.$message.success('删除账户成功')
      } catch (err) {
        this.$message('取消操作')
      }
    },
    reset() {
      this.$refs.form.resetFields()
      this.province = null
      this.city = null
      this.isSearch = false
      this.getCompanysList(this.page)
    }
  }

}
</script>

<style lang="scss" >
.two{
  .distpicker-address-wrapper {
    display: inline-block;
}
}

</style>
